/**
 * Abandoned功能测试
 * 测试任务的放弃和恢复功能
 */

const chalk = require('chalk');
const config = require('../../config/test-config');
const TestUtils = require('../../utils/test-utils');

class AbandonedFunctionalityTest {
  constructor() {
    this.testUtils = new TestUtils(config);
    this.httpClient = this.testUtils.createHttpClient();
    this.testTasks = [];
    this.testLists = [];
  }

  /**
   * 运行所有abandoned功能测试
   */
  async runAllTests() {
    console.log(chalk.cyan('\n🧪 开始测试Abandoned功能...'));
    
    try {
      // 设置测试环境
      await this.setupTestEnvironment();
      
      // 运行测试
      await this.testAbandonTask();
      await this.testRestoreTask();
      await this.testSyncAbandonedTask();
      await this.testFilterAbandonedTasks();
      
      // 清理测试环境
      await this.cleanupTestEnvironment();
      
      console.log(chalk.green('✅ Abandoned功能测试完成'));
    } catch (error) {
      console.error(chalk.red('❌ Abandoned功能测试失败:'), error.message);
      throw error;
    }
  }

  /**
   * 设置测试环境
   */
  async setupTestEnvironment() {
    console.log(chalk.yellow('🔧 设置测试环境...'));
    
    // 创建测试清单
    const listResponse = await this.httpClient.post(config.apiEndpoints.lists.create, {
      name: 'Abandoned测试清单',
      color: '#ff6b6b'
    });
    
    if (listResponse.data && listResponse.data.list) {
      this.testLists.push(listResponse.data.list);
    }

    // 创建测试任务
    const taskData = {
      title: 'Abandoned功能测试任务',
      text: '这是一个用于测试abandoned功能的任务',
      list_id: this.testLists[0]?.id || null,
      priority: 'medium',
      status: 'pending'
    };

    const taskResponse = await this.httpClient.post(config.apiEndpoints.tasks.create, taskData);
    
    if (taskResponse.data && taskResponse.data.task) {
      this.testTasks.push(taskResponse.data.task);
    }
  }

  /**
   * 测试放弃任务功能
   */
  async testAbandonTask() {
    const startTime = Date.now();
    try {
      if (this.testTasks.length === 0) {
        throw new Error('没有可放弃的测试任务');
      }

      const task = this.testTasks[0];
      
      // 更新任务为abandoned状态
      const updateData = {
        abandoned: true,
        status: 'abandoned'
      };

      const response = await this.httpClient.put(
        config.apiEndpoints.tasks.update.replace(':id', task.id),
        updateData
      );

      this.testUtils.validateApiResponse(response, ['task']);

      if (!response.data.task.abandoned) {
        throw new Error('任务abandoned状态更新失败');
      }

      console.log(chalk.green('✅ 放弃任务测试通过'));
      
      this.testUtils.recordTestResult(
        '放弃任务',
        'ABANDONED_FUNCTIONALITY',
        'passed',
        Date.now() - startTime,
        null,
        '测试放弃任务功能'
      );
    } catch (error) {
      console.error(chalk.red('❌ 放弃任务测试失败:'), error.message);
      
      this.testUtils.recordTestResult(
        '放弃任务',
        'ABANDONED_FUNCTIONALITY',
        'failed',
        Date.now() - startTime,
        error.message,
        '测试放弃任务功能'
      );
    }
  }

  /**
   * 测试恢复已放弃任务功能
   */
  async testRestoreTask() {
    const startTime = Date.now();
    try {
      if (this.testTasks.length === 0) {
        throw new Error('没有可恢复的测试任务');
      }

      const task = this.testTasks[0];
      
      // 恢复任务
      const updateData = {
        abandoned: false,
        status: 'pending'
      };

      const response = await this.httpClient.put(
        config.apiEndpoints.tasks.update.replace(':id', task.id),
        updateData
      );

      this.testUtils.validateApiResponse(response, ['task']);

      if (response.data.task.abandoned) {
        throw new Error('任务恢复失败，abandoned状态仍为true');
      }

      console.log(chalk.green('✅ 恢复任务测试通过'));
      
      this.testUtils.recordTestResult(
        '恢复已放弃任务',
        'ABANDONED_FUNCTIONALITY',
        'passed',
        Date.now() - startTime,
        null,
        '测试恢复已放弃任务功能'
      );
    } catch (error) {
      console.error(chalk.red('❌ 恢复任务测试失败:'), error.message);
      
      this.testUtils.recordTestResult(
        '恢复已放弃任务',
        'ABANDONED_FUNCTIONALITY',
        'failed',
        Date.now() - startTime,
        error.message,
        '测试恢复已放弃任务功能'
      );
    }
  }

  /**
   * 测试同步abandoned任务功能
   */
  async testSyncAbandonedTask() {
    const startTime = Date.now();
    try {
      const syncData = {
        tasks: [{
          client_id: 'test-abandoned-sync-' + Date.now(),
          title: '同步测试-已放弃任务',
          text: '这是一个用于测试同步功能的已放弃任务',
          completed: false,
          deleted: false,
          version: 1,
          last_modified_at: new Date().toISOString(),
          list_id: this.testLists[0]?.id || null,
          priority: 'low',
          status: 'abandoned',
          abandoned: true
        }]
      };

      const response = await this.httpClient.post(config.apiEndpoints.tasks.sync, syncData);

      this.testUtils.validateApiResponse(response, ['tasks']);

      const syncedTask = response.data.tasks.find(task => 
        task.client_id === syncData.tasks[0].client_id
      );

      if (!syncedTask || !syncedTask.abandoned) {
        throw new Error('同步abandoned任务失败');
      }

      console.log(chalk.green('✅ 同步abandoned任务测试通过'));
      
      this.testUtils.recordTestResult(
        '同步abandoned任务',
        'ABANDONED_FUNCTIONALITY',
        'passed',
        Date.now() - startTime,
        null,
        '测试同步abandoned任务功能'
      );
    } catch (error) {
      console.error(chalk.red('❌ 同步abandoned任务测试失败:'), error.message);
      
      this.testUtils.recordTestResult(
        '同步abandoned任务',
        'ABANDONED_FUNCTIONALITY',
        'failed',
        Date.now() - startTime,
        error.message,
        '测试同步abandoned任务功能'
      );
    }
  }

  /**
   * 测试过滤abandoned任务功能
   */
  async testFilterAbandonedTasks() {
    const startTime = Date.now();
    try {
      // 获取所有任务
      const response = await this.httpClient.get(config.apiEndpoints.tasks.list);

      this.testUtils.validateApiResponse(response, ['tasks']);

      const abandonedTasks = response.data.tasks.filter(task => task.abandoned === true);
      
      console.log(chalk.blue(`📊 找到 ${abandonedTasks.length} 个已放弃的任务`));

      console.log(chalk.green('✅ 过滤abandoned任务测试通过'));
      
      this.testUtils.recordTestResult(
        '过滤abandoned任务',
        'ABANDONED_FUNCTIONALITY',
        'passed',
        Date.now() - startTime,
        null,
        `测试过滤abandoned任务功能 (找到${abandonedTasks.length}个已放弃任务)`
      );
    } catch (error) {
      console.error(chalk.red('❌ 过滤abandoned任务测试失败:'), error.message);
      
      this.testUtils.recordTestResult(
        '过滤abandoned任务',
        'ABANDONED_FUNCTIONALITY',
        'failed',
        Date.now() - startTime,
        error.message,
        '测试过滤abandoned任务功能'
      );
    }
  }

  /**
   * 清理测试环境
   */
  async cleanupTestEnvironment() {
    console.log(chalk.yellow('🧹 清理测试环境...'));
    
    // 删除测试任务
    for (const task of this.testTasks) {
      try {
        await this.httpClient.delete(config.apiEndpoints.tasks.delete.replace(':id', task.id));
      } catch (error) {
        console.warn(chalk.yellow(`⚠️ 删除测试任务失败: ${error.message}`));
      }
    }

    // 删除测试清单
    for (const list of this.testLists) {
      try {
        await this.httpClient.delete(config.apiEndpoints.lists.delete.replace(':id', list.id));
      } catch (error) {
        console.warn(chalk.yellow(`⚠️ 删除测试清单失败: ${error.message}`));
      }
    }
  }
}

module.exports = AbandonedFunctionalityTest;